package android.dbhelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.util.Log;

/**
 * Login: send <username,password> reply: "__successful__".$token // for correct
 * "__failed__" // for incorrect
 * 
 * Register: send <regUsername,regPassword,email> reply: "__failed__" // for
 * error, not unique nickname "__successful__" // ok
 * 
 * Forgotpass send <username,password> reply "e10adc3949ba59abbe56e057f20f883e"
 * // set new pass 123456 "__failed__" // fail
 * 
 * @author loandt
 * 
 */
public class AccountDbHelper {
	public static final int ACTION_REGISTER = 0;
	public static final int ACTION_LOGIN = 1;
	public static final int ACTION_SET_PASSWORD = 2;
	public static final int ACTION_SET_EMAIL = 3;
	public static final int ACTION_FORGOT_PASSWORD = 4;
	protected String mUsername;
	protected String mPassword;
	protected String mEmail;
	protected String token;
	protected String mResult;

	public AccountDbHelper() {
		mUsername = null;
		mPassword = null;
	}

	/**
	 * CONSTRUCTOR: Create an AccountDbHelper from provided username and
	 * password
	 * 
	 * @param username
	 *            - String
	 * @param password
	 *            - String md5
	 */
	public AccountDbHelper(String username, String password) {
		mUsername = username;
		mPassword = password;
	}

	/**
	 * Create an AccountDbHelper from provided username
	 * 
	 * @param username
	 */
	public AccountDbHelper(String username, String password, String email) {
		mUsername = username;
		mEmail = email;
	}

	public void setUsername(String username) {
		mUsername = username;
	}

	public String getUsername() {
		return mUsername;
	}

	public void setPassword(String password) {
		mPassword = password;
	}

	public String getPassword() {
		return mPassword;
	}

	/**
	 * REGISTER FOR NEW USER
	 * 
	 * @param username
	 *            : String
	 * @param password
	 *            : String md5
	 * @param email
	 *            : String
	 * @return: result of registetration: false or true
	 */
	public boolean actionRegister(String username, String password, String email) {
		return postData(ACTION_REGISTER, username, password, email, null);
	}

	/**
	 * LOGIN INTO SYSTEM
	 * 
	 * @return: result of logining: true or false
	 */
	public String actionLogin() {
		if (postData(ACTION_LOGIN, mUsername, mPassword, null, null) == true)
			return token;
		return mResult;
	}

	/**
	 * CHANGE NEW EMAIL
	 * 
	 * @param email
	 *            : String
	 * @return result of changing: true or false
	 */
	public boolean actionChangeEmail(String email) {
		return postData(ACTION_SET_EMAIL, mUsername, mPassword, email, null);
	}

	/**
	 * CHANGE PASSWORD
	 * 
	 * @param newPassword
	 * @return true or false == successful or failure
	 */
	public boolean actionChangePassword(String newPassword) {
		return postData(ACTION_SET_PASSWORD, mUsername, mPassword, null,
				newPassword);
	}

	public boolean actionForgotPassword() {
		return postData(ACTION_FORGOT_PASSWORD, mUsername, null, mEmail, null);
	}

	/**
	 * POST DATA TO SERVER
	 * 
	 * @param task
	 *            - integer: type of task to do: register, login, change email
	 *            or password
	 * @param username
	 *            - String
	 * @param password
	 *            - String md5
	 * @param newEmail
	 *            - String
	 * @param newPassword
	 *            - String
	 * @return: result of action: true or false
	 */
	public boolean postData(int task, String username, String password,
			String newEmail, String newPassword) {
		String response = null;
		switch (task) {
		case ACTION_REGISTER:
			ArrayList<NameValuePair> registerValues = new ArrayList<NameValuePair>();
			registerValues.add(new BasicNameValuePair("task", "register"));
			registerValues.add(new BasicNameValuePair("regUsername", username));
			registerValues.add(new BasicNameValuePair("regPassword", password));
			registerValues.add(new BasicNameValuePair("regEmail", newEmail));

			// 1) Connect via HTTP. 2) Encode data. 3) Send data.
			response = null;
			try {
				response = CustomHttpClient.executeHttpPost(
						"http://10.0.2.2/3cards/register.php", registerValues); // Enetr
																				// Your
																				// remote
																				// PHP,ASP,
																				// Servlet
																				// file
																				// link
				String res = response.toString();
				res = res.replaceAll("\\s+", "");
				if (res.contains("__successful__")) {
					mResult = "__successful__";
					return true; // duplicate username or email
				} else {
					mResult = "__fail__";
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case ACTION_LOGIN:
			// Add data to be send.

			ArrayList<NameValuePair> loginValues = new ArrayList<NameValuePair>();
			loginValues.add(new BasicNameValuePair("task", "login"));
			loginValues.add(new BasicNameValuePair("username", username));
			loginValues.add(new BasicNameValuePair("password", password));
			Log.i("set data", "ok");
			// 1) Connect via HTTP. 2) Encode data. 3) Send data.
			response = null;
			try {
				response = CustomHttpClient.executeHttpPost(
						"http://10.0.2.2/3cards/login.php", loginValues); // Enetr
																			// Your
																			// remote
																			// PHP,ASP,
																			// Servlet
																			// file
																			// link
				String res = response.toString();
				token = "";
				res = res.replaceAll("\\s+", "");

				if (res.contains("__successful__")) {
					StringTokenizer st = new StringTokenizer(res, "__");
					token = st.nextToken();
					return true;
				} else {
					mResult = "__fail__";
					return false;
				}
			} catch (Exception e) {

				Log.e("Login Exception", e.getMessage());
			}
			break;

		case ACTION_FORGOT_PASSWORD:
			// Add data to be send.
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("username", mUsername));
			nameValuePairs.add(new BasicNameValuePair("email", mEmail));
			Log.i("set data", "ok");
			// 1) Connect via HTTP. 2) Encode data. 3) Send data.
			response = null;
			try {
				response = CustomHttpClient.executeHttpPost(
						"http://10.0.2.2/3cards/resetpass.php", nameValuePairs); // Enetr
																					// Your
																					// remote
																					// PHP,ASP,
																					// Servlet
																					// file
																					// link
				String res = response.toString();

				res = res.replaceAll("\\s+", "");

				if (res.equals("e10adc3949ba59abbe56e057f20f883e")) {
					// createDialog("Success","Your password new is 123456, please change after login");
					return true;
				} else {
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		default:
			break;
		}

		return false;
	}

	/**
	 * READ FROM RESPONSE TO STRING
	 * 
	 * @param inputStream
	 * @return string s that is the response of action from server
	 * @throws IOException
	 */
	public String inputStreamToString(InputStream inputStream)
			throws IOException {
		String s = "";
		String line = "";

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				inputStream));

		// Read response until the end
		while ((line = rd.readLine()) != null) {
			s += line;
		}

		// Return full string
		return s;
	}
}
